package com.lechuang.file.utils;

import cn.hutool.core.lang.Pair;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.lechuang.file.listener.AnalysisClassListener;
import com.lechuang.file.listener.AnalysisMapListener;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *   excel工具封装
 * </p>
 * @author liaoningbo
 * @since 2023/5/22
*/
public class ReadExcelUtils {

    /**
     * <p>
     *   解析Excel，指定某一个sheet（从0开始），指定表头行数，解析结果用实体接收
     * </p>
     * @param file 解析文件
     * @param cla 解析后接收数据的实体对象
     * @param sheetNo 指定解析哪个sheet，从0开始
     * @param headRowNumber 指定表头行数
     * @author liaoningbo
     * @since 2023/5/22
    */
    public static <T> Pair<Map<Integer, String>, List<T>> analysisExcel(MultipartFile file, Class<T> cla, int sheetNo, int headRowNumber){
        try {
            InputStream inputStream = file.getInputStream();
            AnalysisClassListener<T> analysisClassListener = new AnalysisClassListener(cla, headRowNumber);
            EasyExcel.read(inputStream, cla, analysisClassListener)
                    .sheet(sheetNo)
                    .headRowNumber(headRowNumber)
                    .doRead();
            List<T> list = analysisClassListener.getDataList();
            Map<Integer, String> headMap = analysisClassListener.getHeadMap();
            return new Pair<>(headMap, list);
        } catch (IOException e) {
            throw new RuntimeException(JSONUtil.toJsonStr(e));
        }
    }

    /**
     * <p>
     *   解析Excel，指定某一个sheet（从0开始），指定表头行数，解析结果用map接收
     * </p>
     * @param file 解析文件
     * @param sheetNo 指定解析哪个sheet，从0开始
     * @param headRowNumber 指定表头行数
     * @author liaoningbo
     * @since 2023/5/22
     */
    public static Pair<List<Map<Integer, String>>, List<Map<Integer, String>>> analysisExcel(MultipartFile file, int sheetNo, int headRowNumber){
        try {
            AnalysisMapListener analysisMapListener = new AnalysisMapListener();
            InputStream inputStream = file.getInputStream();
            EasyExcelFactory.read(inputStream).registerReadListener(analysisMapListener)
                    .headRowNumber(headRowNumber).sheet(sheetNo).doRead();
            List<Map<Integer, String>> headList = analysisMapListener.getHeadList();
            List<Map<Integer, String>> dataList = analysisMapListener.getDataList();
            return new Pair<>(headList, dataList);
        } catch (IOException e) {
            throw new RuntimeException(JSONUtil.toJsonStr(e));
        }
    }


}
